var express = require('express');
var router = express.Router();
var path = require('path');
var fs = require('fs');
var util = require('util');
var ip = require('my-local-ip');
var moment = require('moment');

const AppReader = require("reiko-parser");

/* GET home page. */
router.get('/', async function(req, res, next) {
  res.render('index', { title: 'Express' });
  res.json(ret);
});

router.get('/list', async function(req, res, next) {
  let ret = await obtainApps(req, req.app.get('appsPath'))
  res.json(ret);
});

async function obtainApps(req, filepath) {

  var infoArray = new Array();
  let files = fs.readdirSync(filepath);

  for (let index = 0; index < files.length; index++) {
    const item = files[index];

    file = path.join(filepath, item);
    if (file.endWith('.ipa')) {

      let result = await parseIpa(file);
      let stat = fs.statSync(file);
      let date = new Date(stat.ctime);
      let port = req.app.get('port');
      let obj = new Object();
      obj.name = result.CFBundleDisplayName || result.CFBundleExecutable;
      obj.filename = item;
      obj.source = item.replace('.ipa', '');
      obj.plist = item.replace('ipa', 'plist');
      obj.icon = result.icon;
      obj.url = "itms-services://?action=download-manifest&url=https://"+ip()+':'+port+'/'+obj.plist;
      obj.ctime = moment(date).format("YYYY年MM月DD日 HH:mm");
      infoArray.push(obj);
    }
  }
  // console.log("------------------");
  // console.log(infoArray);
  return infoArray;
}

function parseIpa(filepath) {
  return new Promise((resolve, reject)=> {
    const reader = new AppReader(filepath, 'ipa', { withIcon: true });
    reader.parse((error, result) => {
      if (error) {
        reject(error);
      }
      // console.log(result);
      resolve(result);
    });
  });
}


String.prototype.endWith=function(endStr){
  var d=this.length-endStr.length;
  return (d>=0&&this.lastIndexOf(endStr)==d)
}

module.exports = router;
